﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace hello_accinv
{
    public partial class ManageCategory : Form
    {
        private Database db;
        public string loginUser;
        private string selectedCategoryID;

        public ManageCategory()
        {
            InitializeComponent();
            db = new Database();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void btnAddNewCategory_Click(object sender, EventArgs e)
        {
            if (btnCategoryAction.Text.Equals("Save changes"))
            {
                if (MessageBox.Show("Save changes?", "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // Do save changes
                    SaveChanges();
                }
            }
            ClearForm();
            
            txtboxNoProduct.Text = "0";

            datagridCategoryList.Enabled = false;
            txtboxCategoryName.ReadOnly = false;
            txtboxCategoryPUnit.ReadOnly = false;
            txtboxCategoryCodename.ReadOnly = false;

            btnCategoryAction2.Enabled = true;
            btnCategoryAction.Enabled = true;

            btnCategoryAction.Text = "Add this category";
            btnCategoryAction.BackColor = Color.GreenYellow;

            btnCategoryAction2.Text = "Cancel";

            txtboxCategoryName.Focus();

            datagridCategoryList.ClearSelection();
        }

        private void btnCategoryAction2_Click(object sender, EventArgs e)
        {
            if (btnCategoryAction2.Text.Equals("Cancel"))
            {
                ResetForm();
            }
            else if (btnCategoryAction2.Text.Equals("Delete this category"))
            {
                if (txtboxNoProduct.Text.Equals("0"))
                {
                    if (MessageBox.Show("Confirm ?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        db.Delete("Category", "CategoryID = '" + selectedCategoryID + "'");
                        db.Insert("ActionLog", "'" + CurrentDateTime.GetDate() + "','" + CurrentDateTime.GetTime() + "','" + loginUser + " deleted category " + txtboxCategoryName.Text + ".'");
                        MessageBox.Show("Category deleted", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadTableCategory();
                        ResetForm();
                    }
                }
                else
                {
                    MessageBox.Show("Cannot delete while there is product in this category", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void ClearForm()
        {
            txtboxCategoryName.Text = "";
            txtboxCategoryPUnit.Text = "";
            txtboxCategoryCodename.Text = "";
            txtboxNoProduct.Text = "";
            lbProductUnit.Text = "Unit";
        }

        private void ManageCategory_Load(object sender, EventArgs e)
        {
            LoadTableCategory();
        }

        private void LoadTableCategory()
        {
            DataTable dt = db.Select("Name AS CName, Codename AS CCodename", "Category", "1 ORDER BY Name ASC");
            datagridCategoryList.DataSource = dt;
            datagridCategoryList.ClearSelection();
        }

        private void datagridCategoryList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (datagridCategoryList.SelectedRows.Count > 0)
            {
                LoadCategoryDetail();
                btnCategoryAction2.Enabled = true;
                btnCategoryAction.Enabled = true;
            }
        }

        private void LoadCategoryDetail()
        {
            DataTable dt = db.Select("CategoryID, Unit", 
                                     "Category", 
                                     "Name = '" + datagridCategoryList.SelectedRows[0].Cells["CName"].Value + "'");
            selectedCategoryID = dt.Rows[0]["CategoryID"].ToString();
            string unit = dt.Rows[0]["Unit"].ToString();

            dt = db.Select("COUNT(PCODE) AS Count", "Product", "CategoryID = '" + selectedCategoryID + "'");
            string productCount = dt.Rows[0]["Count"].ToString();

            txtboxCategoryName.Text = datagridCategoryList.SelectedRows[0].Cells["CName"].Value.ToString();
            txtboxCategoryPUnit.Text = unit;
            txtboxCategoryCodename.Text = datagridCategoryList.SelectedRows[0].Cells["CCodename"].Value.ToString();
            txtboxNoProduct.Text = productCount;
        }

        private void txtboxCategoryPUnit_TextChanged(object sender, EventArgs e)
        {
            lbProductUnit.Text = txtboxCategoryPUnit.Text;
        }

        private void btnCategoryAction_Click(object sender, EventArgs e)
        {
            if (btnCategoryAction.Text.Equals("Add this category"))
            {
                if (IsValidate() && ChkConflict())
                {
                    // Get latest category id
                    DataTable dt = db.Select("CategoryID",
                                             "Category",
                                             "1 ORDER BY CAST(CategoryID AS DECIMAL) DESC LIMIT 1");
                    int newCategoryID = 1;
                    if (dt.Rows.Count > 0)
                    {
                        newCategoryID = Int32.Parse(dt.Rows[0]["CategoryID"].ToString()) + 1;
                    }

                    db.Insert("Category",
                              "'" + newCategoryID + "','" + txtboxCategoryName.Text + "','" + txtboxCategoryPUnit.Text + "','" + txtboxCategoryCodename.Text + "'");
                    db.Insert("ActionLog", "'" + CurrentDateTime.GetDate() + "','" + CurrentDateTime.GetTime() + "','" + loginUser + " added category " + txtboxCategoryName.Text + ".'");

                    
                    MessageBox.Show("Category added", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    datagridCategoryList.Enabled = true;
                    ResetForm();
                    LoadTableCategory();
                }
                else
                {
                    MessageBox.Show("Recheck category detail", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (btnCategoryAction.Text.Equals("Edit category detail"))
            {
                txtboxCategoryName.ReadOnly = false;
                txtboxCategoryPUnit.ReadOnly = false;
                txtboxCategoryCodename.ReadOnly = false;
                datagridCategoryList.Enabled = false;

                txtboxCategoryName.Focus();

                btnCategoryAction.BackColor = Color.GreenYellow;
                btnCategoryAction.Text = "Save changes";

                btnCategoryAction2.Text = "Cancel";
            }
            else if (btnCategoryAction.Text.Equals("Save changes"))
            {
                SaveChanges();
                datagridCategoryList.Enabled = true;
            }
        }

        private bool IsValidate()
        {
            bool validate = true;

            validate = (txtboxCategoryName.Text.Length > 0) ? true : false;
            validate = (txtboxCategoryPUnit.Text.Length > 0) ? true : false;
            validate = (txtboxCategoryCodename.Text.Length == 3) ? true : false;

            return validate;
        }

        private void ResetForm()
        {
            ClearForm();

            datagridCategoryList.Enabled = true;
            txtboxCategoryName.ReadOnly = true;
            txtboxCategoryPUnit.ReadOnly = true;
            txtboxCategoryCodename.ReadOnly = true;

            btnCategoryAction2.Enabled = false;
            btnCategoryAction.Enabled = false;

            btnCategoryAction.Text = "Edit category detail";
            btnCategoryAction.BackColor = Color.LemonChiffon;

            btnCategoryAction2.Text = "Delete this category";
        }

        private void SaveChanges()
        {
            if (IsValidate())
            {
                db.Update("Category",
                          "Name = '" + txtboxCategoryName.Text + "', Unit = '" + txtboxCategoryPUnit.Text + "', Codename = '" + txtboxCategoryCodename.Text + "'",
                          "CategoryID = '" + selectedCategoryID + "'");
                db.Insert("ActionLog", "'" + CurrentDateTime.GetDate() + "','" + CurrentDateTime.GetTime() + "','" + loginUser + " edited category " + txtboxCategoryName.Text + ".'");
                
                MessageBox.Show("Category updated");

                ResetForm();
                LoadTableCategory();
            }
            else
            {
                MessageBox.Show("Recheck category detail", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool ChkConflict()
        {
            for (int i = 0; i < datagridCategoryList.RowCount; ++i)
                if (datagridCategoryList.Rows[i].Cells["CName"].Value.ToString().Equals(txtboxCategoryName.Text) ||
                    datagridCategoryList.Rows[i].Cells["CCodename"].Value.ToString().Equals(txtboxCategoryCodename.Text))
                    return false;
            return true;
        }
    }
}
